<template>
  <div class="app-container">
    <el-form :inline="true" label-width="68px">
      <el-form-item label="看诊时间">
        <date-picker :value="seeingTime" @input="handleSeeingTime"></date-picker>
      </el-form-item>
      <el-form-item>
        <columns-filter-button></columns-filter-button>
      </el-form-item>
      <el-form-item label="TC" prop="userId" class="datetimerange">
        <el-select
          v-model="queryParams.userId"
          filterable
          clearable
          placeholder="请选择TC"
          @change="selectTC"
        >
          <el-option
            v-for="item in tcList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      border
      stripe
      :data="seeingList"
      :height="clientHeight"
      :max-height="clientHeight"
      @row-dblclick="handleDetails"
      @cell-click="handleCellClick"
      @filter-change="handleFilterChange"
    >
      <el-table-column type="index" fixed="left"></el-table-column>

      <columns-filter-view>
        <el-table-column align="center" label="姓名" min-width="120">
          <div
            v-if="scope.row.yiyaClinicPerson && scope.row.yiyaClinicPerson.name"
            slot-scope="scope"
            style="cursor: pointer"
          >{{ scope.row.yiyaClinicPerson.name }}</div>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column label="头像" align="center" prop="imageUrl" :min-width="'头像'">
          <avatar-image slot-scope="scope" :patient="scope.row.yiyaClinicPerson"></avatar-image>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column align="center" label="手机号码" min-width="180">
          <hover-phone slot-scope="scope" :type="1" :items="scope.row.yiyaClinicPerson" />
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column align="center" label="性别" prop="yiyaClinicPerson.sex"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column align="center" label="年龄" prop="yiyaClinicPerson.age"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          align="center"
          label="看诊门诊"
          prop="yiyaClinicPerson.arriveClinic"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <!--      <columns-filter-view>-->
      <!--        <el-table-column align="center" label="跟踪状态"> </el-table-column>-->
      <!--      </columns-filter-view>-->
      <!--      <columns-filter-view>-->
      <!--        <el-table-column align="center" label="消费状态"> </el-table-column>-->
      <!--      </columns-filter-view>-->
      <columns-filter-view>
        <el-table-column align="center" label="开单状态" :min-width="'到店状态'.length * 30">
          <template
            slot-scope="scope"
          >{{ userBillingStatusEnum[scope.row.yiyaClinicPerson.billingState] }}</template>
        </el-table-column>
      </columns-filter-view>
      <!--      <columns-filter-view>-->
      <!--        <el-table-column align="center" label="成交状态"></el-table-column>-->
      <!--      </columns-filter-view>-->
      <columns-filter-view>
        <el-table-column
          align="center"
          label="初诊TC"
          min-width="100"
          column-key="firstTc"
          :filters="tcOptions"
          prop="yiyaClinicPerson.firstTc"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          align="center"
          label="初诊时间"
          min-width="160"
          prop="yiyaClinicPerson.firstDiagnoseTime"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column align="center" label="看诊人" prop="yiyaDiagnoseRunning.userName"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          align="center"
          label="看诊内容"
          min-width="160"
          prop="yiyaDiagnoseRunning.result"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          align="center"
          label="看诊时间"
          min-width="160"
          prop="yiyaDiagnoseRunning.createTime"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="操作" align="center" min-width="100">
          <el-dropdown slot-scope="scope">
            <span class="el-dropdown-link">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleAdd(scope.row.yiyaClinicPerson)">新建看诊</el-dropdown-item>
              <el-dropdown-item @click.native="handleEdit(scope.row.yiyaDiagnoseRunning)">编辑看诊</el-dropdown-item>
              <el-dropdown-item @click.native="handleDelete(scope.row.yiyaDiagnoseRunning)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>
    <pagination
      v-show="total > 0"
      style="position: fixed; right: 20px; bottom: 20px"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListRunning"
    ></pagination>
  </div>
</template>

<script>
import {
  addRunning,
  delRunning,
  listRunningAll,
  updateRunning,
} from '@/api/services/running'
import { encode } from '@/utils/utils'
import {
  formatStartWithEnd,
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getTomorrowStartWithEnd,
} from '@/utils/date'

import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import TablePhone from '@/components/yiya/TablePhone'
import Empty from '@/components/yiya/Empty'
import { consumptionStatusEnum, userBillingStatusEnum } from '@/utils/enums'
import { mapState } from 'vuex'
import { listStaff } from '@/api/services/common'
import DatePicker from '@/components/yiya/DatePicker/index'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,

  orderByColumn: 'createTime',
  isAsc: 'desc',
  beginTime: undefined,
  endTime: undefined,
  userId: '',
  firstTc: undefined,
}

export default {
  name: 'SeeingRecord',
  components: {
    DatePicker,
    ColumnsFilterButton,
    ColumnsFilterView,
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    Empty,
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      loading: true,
      total: 0,
      queryParams: {},
      seeingList: [],
      clientHeight: document.body.clientHeight - 225,
      seeingTime: [],
      tcList: [],
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
      userName: (state) => state.user.name,
      userId: (state) => state.user.userId,
    }),
    tcOptions() {
      return this.tcList.map(({ userName }) => ({
        text: userName,
        value: userName,
      }))
    },
    consumptionStatusEnum() {
      return consumptionStatusEnum
    },
    userBillingStatusEnum() {
      return userBillingStatusEnum
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      clinicId: +this.clinicId,
      orderByColumn: 'createTime',
      isAsc: 'desc',
    }
    const today = getTodayStartWithEnd()
    this.handleSeeingTime(today)
    this.getTcList()
  },
  methods: {
    selectTC(e) {
      this.queryParams.userId = e
      this.resetRouter()
    },
    async resetRouter() {
      this.$store.dispatch('pathQurey/setMarketQuery', {
        path: this.$route.path,
        data: this.queryParams,
      })
      await this.getListRunning()
    },
    handleCellClick(row, column) {
      if (column.label === '姓名') {
        this.handleDetails(row)
      }
    },
    async getListRunning() {
      try {
        this.loading = true
        const { rows, total } = await listRunningAll(this.queryParams)
        this.seeingList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    handleDetails(row) {
      const menu = this.$route.path.slice(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(
        `${menu}/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getListRunning()
    },
    handleSeeingTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.seeingTime = time
      this.queryParams.beginTime  = start
      this.queryParams.endTime  = end
      this.handleQuery()
    },
    handleFilterChange(e) {
      const [key, value] = Object.entries(e)[0]
      this.queryParams[key] = value.join(',')
      this.handleQuery()
    },
    async handleAdd(patient) {
      const { value: result } = await this.$prompt('看诊内容', '添加看诊记录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder:
          '可填写顾客主诉、检查发现、是否面诊、设计方案、是否成交、可开发的、未成交原因等',
        inputValidator: (e) => !!(e && e.trim()),
        inputErrorMessage: '看诊内容不能为空',
      })
      await addRunning({
        result,
        userName: this.userName,
        userId: this.userId,
        clinicPersonId: patient.id,
      })
      this.msgSuccess('添加成功')
      await this.getListRunning()
    },
    async handleEdit(seeing) {
      const { value: result } = await this.$prompt('看诊内容', '编辑看诊记录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: seeing.result,
        inputPlaceholder:
          '可填写顾客主诉、检查发现、是否面诊、设计方案、是否成交、可开发的、未成交原因等',
        inputValidator: (e) => !!(e && e.trim()),
        inputErrorMessage: '看诊内容不能为空',
      })
      await updateRunning({
        id: seeing.id,
        result,
      })
      this.msgSuccess('编辑成功')
      await this.getListRunning()
    },
    async handleDelete(seeing) {
      await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await delRunning(seeing.id)
      this.msgSuccess('删除成功')
      await this.getListRunning()
    },
  },
}
</script>

